﻿using System;
using System.Net;
using System.Text;
using System.Windows;
using eLearning.Model;
using eLearning.Util;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Newtonsoft.Json;

namespace eLearning.DosenView
{
    public partial class PerkuliahanSelectPage : PhoneApplicationPage
    {
        private bool firstLoaded;

        public PerkuliahanSelectPage()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (e.NavigationMode != System.Windows.Navigation.NavigationMode.Back)
            {
                LoadPerkuliahan();
            }
        }

        private void LoadPerkuliahan()
        {
            DetailMatkul kuliah = new DetailMatkul();
            kuliah.Creator = (Dosen)SavedUser.Instance.User.ConvertUser();
            string json = JsonConvert.SerializeObject(kuliah);

            string url = Config.Instance.PERKULIAHAN_SERVICE_URL() + Config.PERKULIAHAN_DOSEN_VIEW_KEY;

            string urlformat = string.Format("{0}&{1}", url, Guid.NewGuid().ToString());
            Uri uri = new Uri(urlformat, UriKind.Absolute);

            WebClient webClient = new WebClient();
            webClient.Encoding = Encoding.UTF8;
            webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
            webClient.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();
            webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(listPerkuliahan_UploadStringCompleted);
            webClient.UploadStringAsync(uri, "POST", json);
        }

        private void listPerkuliahan_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                DetailMatkulList list = JsonConvert.DeserializeObject<DetailMatkulList>(e.Result);
                matkulList.ItemsSource = list;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void buttonSave_Click(object sender, System.EventArgs e)
        {
            Utility.GotoPage(this, "/View/Dosen/QuestionPage.xaml");
            PhoneApplicationService.Current.State[Config.DETMATKUL] = matkulList.SelectedItem;
        }

    }
}